<template>
  <div class="order-processing">
    <!-- 页面头部 -->
    <div class="page-header">
      <h2>订单处理</h2>
      <p>处理分配给本站点的订单，管理订单状态</p>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-row :gutter="16">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-icon pending">
                <el-icon><Clock /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ stats.pending }}</div>
                <div class="stat-label">待处理</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-icon processing">
                <el-icon><Loading /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ stats.processing }}</div>
                <div class="stat-label">处理中</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-icon completed">
                <el-icon><Check /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ stats.completed }}</div>
                <div class="stat-label">已完成</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-icon revenue">
                <el-icon><Money /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">¥{{ stats.todayRevenue }}</div>
                <div class="stat-label">今日收益</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 筛选和操作栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <el-select 
          v-model="filters.status" 
          placeholder="订单状态"
          clearable
          style="width: 150px"
          @change="loadOrders"
        >
          <el-option label="待确认" value="pending" />
          <el-option label="已确认" value="confirmed" />
          <el-option label="处理中" value="in_progress" />
          <el-option label="已完成" value="completed" />
          <el-option label="已取消" value="cancelled" />
        </el-select>
        <el-date-picker
          v-model="filters.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="width: 240px; margin-left: 12px"
          @change="loadOrders"
        />
        <el-button icon="Refresh" @click="loadOrders" style="margin-left: 12px">
          刷新
        </el-button>
      </div>
      <div class="toolbar-right">
        <el-input 
          v-model="filters.keyword" 
          placeholder="搜索订单号、客户"
          clearable
          style="width: 250px"
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
    </div>

    <!-- 订单列表 -->
    <el-card class="table-card">
      <el-table 
        v-loading="loading" 
        :data="orders" 
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="orderNo" label="订单号" width="150" />
        <el-table-column prop="customerName" label="客户" width="120" />
        <el-table-column prop="customerPhone" label="联系电话" width="130" />
        <el-table-column prop="pickupAddress" label="取货地址" min-width="200" show-overflow-tooltip />
        <el-table-column prop="pickupTime" label="预约时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.pickupTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="totalAmount" label="金额" width="100">
          <template #default="{ row }">
            <span class="amount">¥{{ row.totalAmount.toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="totalWeight" label="重量" width="100">
          <template #default="{ row }">
            {{ row.totalWeight }}kg
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button 
              v-if="row.status === 'pending'"
              type="primary" 
              link 
              size="small" 
              @click="handleConfirm(row)"
            >
              确认
            </el-button>
            <el-button 
              v-if="row.status === 'confirmed'"
              type="success" 
              link 
              size="small" 
              @click="handleStartProcessing(row)"
            >
              开始处理
            </el-button>
            <el-button 
              v-if="row.status === 'in_progress'"
              type="warning" 
              link 
              size="small" 
              @click="handleComplete(row)"
            >
              完成
            </el-button>
            <el-button type="info" link size="small" @click="handleViewDetails(row)">
              详情
            </el-button>
            <el-button 
              v-if="['pending', 'confirmed'].includes(row.status)"
              type="danger" 
              link 
              size="small" 
              @click="handleCancel(row)"
            >
              取消
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 订单详情对话框 -->
    <el-dialog 
      v-model="detailDialogVisible" 
      title="订单详情"
      width="800px"
    >
      <div v-if="selectedOrder" class="order-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单号">{{ selectedOrder.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getStatusType(selectedOrder.status)">
              {{ getStatusText(selectedOrder.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="客户姓名">{{ selectedOrder.customerName }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ selectedOrder.customerPhone }}</el-descriptions-item>
          <el-descriptions-item label="取货地址" :span="2">{{ selectedOrder.pickupAddress }}</el-descriptions-item>
          <el-descriptions-item label="预约时间">{{ formatDateTime(selectedOrder.pickupTime) }}</el-descriptions-item>
          <el-descriptions-item label="实际取货时间">
            {{ selectedOrder.actualPickupTime ? formatDateTime(selectedOrder.actualPickupTime) : '未设置' }}
          </el-descriptions-item>
          <el-descriptions-item label="订单金额">¥{{ selectedOrder.totalAmount.toFixed(2) }}</el-descriptions-item>
          <el-descriptions-item label="订单重量">{{ selectedOrder.totalWeight }}kg</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDateTime(selectedOrder.createdAt) }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ selectedOrder.notes || '无' }}</el-descriptions-item>
        </el-descriptions>

        <!-- 订单物品明细 -->
        <div class="order-items" style="margin-top: 20px;">
          <h4>回收物品明细</h4>
          <el-table :data="selectedOrder.items" border>
            <el-table-column label="物品名称">
              <template #default="{ row }">
                {{ row.item?.name || row.itemName || '未知物品' }}
              </template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量" width="80" />
            <el-table-column prop="unitPrice" label="单价" width="80">
              <template #default="{ row }">
                ¥{{ row.unitPrice.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column prop="subtotal" label="小计" width="100">
              <template #default="{ row }">
                ¥{{ row.subtotal.toFixed(2) }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button 
            v-if="selectedOrder?.status === 'confirmed'"
            type="success" 
            @click="handleStartProcessingFromDetail"
          >
            开始处理
          </el-button>
          <el-button 
            v-if="selectedOrder?.status === 'in_progress'"
            type="warning" 
            @click="handleCompleteFromDetail"
          >
            完成订单
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 确认订单对话框 -->
    <el-dialog 
      v-model="confirmDialogVisible" 
      title="确认订单"
      width="500px"
    >
      <el-form ref="confirmFormRef" :model="confirmForm" :rules="confirmRules" label-width="120px">
        <el-form-item label="实际取货时间" prop="actualPickupTime">
          <el-date-picker
            v-model="confirmForm.actualPickupTime"
            type="datetime"
            placeholder="选择实际取货时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="confirmForm.notes"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="confirmDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="submitConfirm">
          确认订单
        </el-button>
      </template>
    </el-dialog>

    <!-- 完成订单对话框 -->
    <el-dialog 
      v-model="completeDialogVisible" 
      title="完成订单"
      width="600px"
    >
      <div v-if="selectedOrder">
        <p>请确认实际回收的物品信息：</p>
        <el-table :data="actualItems" border>
          <el-table-column prop="itemName" label="物品名称" />
          <el-table-column label="预计数量" width="100">
            <template #default="{ row }">
              {{ row.quantity }}
            </template>
          </el-table-column>
          <el-table-column label="实际数量" width="120">
            <template #default="{ $index }">
              <el-input-number 
                v-model="actualItems[$index].actualQuantity" 
                :min="0" 
                :precision="0"
                size="small"
              />
            </template>
          </el-table-column>
          <el-table-column label="实际单价" width="120">
            <template #default="{ $index }">
              <el-input-number 
                v-model="actualItems[$index].actualPrice" 
                :min="0" 
                :precision="2"
                size="small"
              />
            </template>
          </el-table-column>
          <el-table-column label="实际小计" width="100">
            <template #default="{ $index }">
              ¥{{ (actualItems[$index].actualQuantity * actualItems[$index].actualPrice).toFixed(2) }}
            </template>
          </el-table-column>
        </el-table>
        <div style="margin-top: 16px; text-align: right;">
          <strong>实际总金额: ¥{{ actualTotalAmount.toFixed(2) }}</strong>
        </div>
      </div>
      <template #footer>
        <el-button @click="completeDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="submitComplete">
          确认完成
        </el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import { ordersAPI } from '@/api'
import { useStore } from 'vuex'

const store = useStore()
const router = useRouter()
const route = useRoute()

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const orders = ref([])
const selectedRows = ref([])
const selectedOrder = ref(null)

// 对话框控制
const detailDialogVisible = ref(false)
const confirmDialogVisible = ref(false)
const completeDialogVisible = ref(false)

// 表单引用
const confirmFormRef = ref(null)

// 统计数据
const stats = reactive({
  pending: 5,
  processing: 3,
  completed: 12,
  todayRevenue: 1280.50
})

// 筛选条件
const filters = reactive({
  status: null,
  dateRange: [],
  keyword: ''
})

// 分页数据
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 确认表单
const confirmForm = reactive({
  actualPickupTime: null,
  notes: ''
})

// 确认表单验证规则
const confirmRules = {
  actualPickupTime: [
    { required: true, message: '请选择实际取货时间', trigger: 'change' }
  ]
}

// 实际回收物品
const actualItems = ref([])

// 计算属性
const actualTotalAmount = computed(() => {
  return actualItems.value.reduce((total, item) => {
    return total + (item.actualQuantity * item.actualPrice)
  }, 0)
})

// 方法
const loadOrders = async () => {
  loading.value = true
  try {
    const stationId = store.state.currentStation?.id
    
    const params = {
      page: pagination.page,
      pageSize: pagination.pageSize,
      stationId: stationId || 1, // 当前站点ID
      ...filters
    }
    
    if (filters.dateRange && filters.dateRange.length === 2) {
      params.startDate = filters.dateRange[0]
      params.endDate = filters.dateRange[1]
    }
    
    const response = await ordersAPI.getStationOrders(params.stationId, params)
    
    const orderList = response.list || response.data || response || []
    
    orders.value = orderList
    pagination.total = response.total || orderList.length || 0
  } catch (error) {
    console.error('加载订单失败:', error)
    ElMessage.error('加载订单列表失败')
  } finally {
    loading.value = false
  }
}

const loadStats = async () => {
  try {
    const stationId = store.state.currentStation?.id || 1
    
    // 获取统计数据（后端会统计所有状态的订单数和今日收益）
    const response = await ordersAPI.getOrdersStats({
      stationId,
      startDate: new Date().toISOString().split('T')[0],  // 今天的日期（用于计算今日收益）
      endDate: new Date().toISOString().split('T')[0]
    })
    
    // 更新统计数据
    Object.assign(stats, response)
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

const handleSearch = () => {
  pagination.page = 1
  loadOrders()
}

const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.page = 1
  loadOrders()
}

const handleCurrentChange = (page) => {
  pagination.page = page
  loadOrders()
}

const handleViewDetails = async (row) => {
  try {
    // 获取完整的订单详情（包含物品明细）
    const response = await ordersAPI.getOrderById(row.id)
    
    const orderDetail = response.order || response
    const items = response.items || orderDetail.items || []
    
    selectedOrder.value = {
      ...orderDetail,
      items: items
    }
    
    detailDialogVisible.value = true
  } catch (error) {
    console.error('获取订单详情失败:', error)
    ElMessage.error('获取订单详情失败')
  }
}

const handleConfirm = (row) => {
  selectedOrder.value = row
  confirmForm.actualPickupTime = new Date()
  confirmForm.notes = ''
  confirmDialogVisible.value = true
}

const submitConfirm = async () => {
  if (!confirmFormRef.value) return
  
  try {
    await confirmFormRef.value.validate()
    submitting.value = true
    
    await ordersAPI.confirmOrder(selectedOrder.value.id, {
      stationId: store.state.currentStation?.id || 1,
      actualPickupTime: confirmForm.actualPickupTime.toISOString(),
      notes: confirmForm.notes
    })
    
    ElMessage.success('订单确认成功')
    confirmDialogVisible.value = false
    loadOrders()
    loadStats() // 更新统计数据
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('订单确认失败')
    }
  } finally {
    submitting.value = false
  }
}

const handleStartProcessing = async (row) => {
  try {
    await ElMessageBox.confirm('确定开始处理这个订单吗？', '开始处理', {
      type: 'warning',
      confirmButtonText: '开始处理',
      cancelButtonText: '取消'
    })
    
    submitting.value = true
    
    await ordersAPI.startProcessing(row.id, {
      actualPickupTime: new Date().toISOString()
    })
    
    ElMessage.success('订单已开始处理')
    loadOrders()
    loadStats()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  } finally {
    submitting.value = false
  }
}

// 从详情对话框开始处理订单
const handleStartProcessingFromDetail = async () => {
  detailDialogVisible.value = false
  await handleStartProcessing(selectedOrder.value)
}

// 从详情对话框完成订单
const handleCompleteFromDetail = async () => {
  detailDialogVisible.value = false
  await handleComplete(selectedOrder.value)
}

const handleComplete = async (row) => {
  try {
    // 获取完整的订单详情（包含物品明细）
    const response = await ordersAPI.getOrderById(row.id)
    
    const orderDetail = response.order || response
    const items = response.items || orderDetail.items || []
    
    selectedOrder.value = orderDetail
    
    // 初始化实际回收物品数据
    if (items && items.length > 0) {
      actualItems.value = items.map(item => ({
        ...item,
        itemName: item.itemName || item.item?.name || '未知物品',
        actualQuantity: item.quantity,
        actualPrice: item.unitPrice
      }))
    } else {
      // 如果没有订单项，创建一个空数组
      actualItems.value = []
      ElMessage.warning('该订单没有物品信息')
    }
    
    completeDialogVisible.value = true
  } catch (error) {
    console.error('获取订单详情失败:', error)
    ElMessage.error('获取订单详情失败')
  }
}

const submitComplete = async () => {
  try {
    submitting.value = true
    
    await ordersAPI.completeOrder(selectedOrder.value.id, {
      actualItems: actualItems.value.map(item => ({
        itemId: item.itemId,
        actualQuantity: item.actualQuantity,
        actualPrice: item.actualPrice
      }))
    })
    
    ElMessage.success('订单已完成')
    completeDialogVisible.value = false
    loadOrders()
    loadStats() // 更新统计数据
  } catch (error) {
    ElMessage.error('完成订单失败')
  } finally {
    submitting.value = false
  }
}

const handleCancel = async (row) => {
  try {
    const { value: reason } = await ElMessageBox.prompt(
      '请输入取消原因',
      '取消订单',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputType: 'textarea'
      }
    )
    
    await ordersAPI.cancelOrder(row.id, reason)
    ElMessage.success('订单已取消')
    loadOrders()
    loadStats() // 更新统计数据
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('取消订单失败')
    }
  }
}

const getStatusType = (status) => {
  const statusTypes = {
    pending: 'warning',
    confirmed: 'primary',
    in_progress: 'success',
    completed: 'success',
    cancelled: 'danger'
  }
  return statusTypes[status] || 'info'
}

const getStatusText = (status) => {
  const statusTexts = {
    pending: '待确认',
    confirmed: '已确认',
    in_progress: '处理中',
    completed: '已完成',
    cancelled: '已取消'
  }
  return statusTexts[status] || '未知'
}

const formatDateTime = (datetime) => {
  if (!datetime) return ''
  return new Date(datetime).toLocaleString('zh-CN')
}

// 初始化站点信息
const initStationInfo = async () => {
  try {
    // 如果 store 中没有 currentStation，则重新获取
    if (!store.state.currentStation) {
      const user = store.state.user
      if (user && user.id) {
        const { stationsAPI } = await import('@/api')
        const response = await stationsAPI.getStations({ 
          managerId: user.id,
          page: 1,
          pageSize: 1
        })
        
        const stationList = response.list || response.data || response || []
        
        if (stationList.length > 0) {
          store.commit('SET_CURRENT_STATION', stationList[0])
        } else {
          console.warn('未找到该用户管理的站点')
        }
      }
    }
  } catch (error) {
    console.error('获取站点信息失败:', error)
  }
}

// 生命周期
onMounted(async () => {
  await initStationInfo()
  await loadOrders()
  loadStats()
  
  // 检查是否需要自动打开完成订单对话框
  const completeOrderId = route.query.completeOrderId
  const action = route.query.action
  
  if (completeOrderId && action === 'complete') {
    console.log('自动打开完成订单对话框，订单ID:', completeOrderId)
    
    // 等待订单列表加载完成后，查找对应的订单
    setTimeout(async () => {
      try {
        // 直接调用handleComplete，传入订单ID对象
        await handleComplete({ id: parseInt(completeOrderId) })
        
        // 清除URL参数，避免刷新页面时重复打开
        router.replace({ path: '/station/orders' })
      } catch (error) {
        console.error('自动打开完成订单对话框失败:', error)
        ElMessage.error('打开完成订单对话框失败，请手动操作')
      }
    }, 500)
  }
})
</script>

<style scoped>
.order-processing {
  padding: 24px;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #333;
}

.page-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.stats-cards {
  margin-bottom: 24px;
}

.stat-card {
  height: 100px;
}

.stat-item {
  display: flex;
  align-items: center;
  height: 100%;
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 24px;
  color: white;
}

.stat-icon.pending {
  background: #e6a23c;
}

.stat-icon.processing {
  background: #409eff;
}

.stat-icon.completed {
  background: #67c23a;
}

.stat-icon.revenue {
  background: #f56c6c;
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.toolbar-left {
  display: flex;
  align-items: center;
}

.table-card {
  margin-bottom: 24px;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.amount {
  color: #67c23a;
  font-weight: 500;
}

.order-detail {
  padding: 16px 0;
}

.order-items h4 {
  margin: 0 0 12px 0;
  color: #333;
}
</style>



